package com.develop.skwen.basemodule.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.develop.skwen.basemodule.presenter.BasePresenter;
import com.develop.skwen.basemodule.view.BaseVu;

/**
 * Created by skwen
 * on 18-5-29
 */

public abstract class BaseFragment<P extends BasePresenter,V extends BaseVu> extends Fragment {


    private boolean isVisibleToUser,isViewCreated;
    private P mPresenter;

    private V mVu;


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (isVisibleToUser){
            load();
        }
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
        load();
    }

    private void load() {
        if (isVisibleToUser && isViewCreated){
            onBind();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        preBind(savedInstanceState);
        try {
            mVu = getVuClass().newInstance();
            mVu.setActivity(getActivity());
            mPresenter = getPresenter();
            mVu.setPresenter(getPresenter());
            mVu.init(inflater,container);
            return mVu.getView();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    protected abstract Class<? extends V> getVuClass();

    protected abstract P getPresenter();

    protected void preBind(Bundle savedInstanceState) {

    }

    protected abstract void onBind();


    protected V getVu(){
        return mVu;
    }

}
